package com.lian.hope.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lian.hope.mapper.ProjectsDonationsMapper;
import com.lian.hope.mapper.ProjectsMapper;
import com.lian.hope.model.dto.ProjectsDTO;
import com.lian.hope.model.dto.ProjectsDonationsDTO;
import com.lian.hope.model.po.Projects;
import com.lian.hope.model.po.ProjectsDonations;
import com.lian.hope.model.vo.PageBean;
import com.lian.hope.model.vo.ProjectsVO;
import com.lian.hope.service.ProjectsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class ProjectsServiceImpl implements ProjectsService {

    private final ProjectsMapper projectsMapper;
    private final ProjectsDonationsMapper projectsDonationsMapper;

    /**
     * 分页获取项目列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageBean<ProjectsVO> listProjects(Integer pageNum, Integer pageSize) {
        // 1.创建PageBean对象
        PageBean<ProjectsVO> page = new PageBean<>();
        // 2.开启分页查询
        PageHelper.startPage(pageNum, pageSize);

        // 3.查询mapper
        List<ProjectsVO> list = projectsMapper.listProjects();
        Page<ProjectsVO> projects = (Page<ProjectsVO>)list;

        // 把数据填充到PageBean对象中
        page.setTotal(projects.getTotal());
        page.setItem(projects.getResult());
        return page;
    }

    /**
     * 新增项目
     *
     * @param projects
     * @param userId
     */
    @Override
    public void insertProjects(ProjectsDTO projects, Long userId) {
        Projects p = Projects.builder().projectName(projects.getProjectName()).brief(projects.getBrief())
            .implementationPlan(projects.getImplementationPlan()).projectDescHtml(projects.getProjectDescHtml())
            .targetAmount(projects.getTargetAmount()).createTime(LocalDateTime.now()).userId(userId).imgUrl(projects.getImgUrl()).build();

        projectsMapper.insertProjects(p);
    }

    /**
     * 随机获取一个项目
     *
     * @return
     */
    @Override
    public ProjectsVO getRandomProjects() {
        return projectsMapper.getRandomProjects();
    }

    @Override
    public void insertDonations(Long projectId, ProjectsDonationsDTO projectsDonationsDTO, Long userId) {
        ProjectsDonations projectsDonations = ProjectsDonations.builder().projectId(projectId)
            .amount(projectsDonationsDTO.getAmount()).userId(userId).build();
        projectsDonationsMapper.insertDonations(projectsDonations);
    }

    @Override
    public ProjectsVO getProjectById(Long id) {
      return projectsMapper.getProjectById(id);
    }
}
